<?php
/**
 * 简单 Database 类
 * @author willzhou <willzhou@foxmail.com>
 * @version 2009-05-25 22:34
 */

class database
{
	public $querynum = 0;
	private $db_host = null;
	private $db_user = null;
	private $db_password = null;
	private $db_name = null;
	private $error = array();
	public $is_halt = false;
	public $res = null;

	/**
	 * 构造函数
	 *
	 * @param string $host
	 * @param string $user
	 * @param string $password
	 * @param string $dbname
	 * @param boolean $is_halt
	 */
	public function __construct($host , $user , $password , $dbname , $is_halt = true) {
		$this->db_host = $host;
		$this->db_user = $user;
		$this->db_password = $password;
		$this->db_name = $dbname;
		$this->is_halt = $is_halt;

		$this->connect();
	}

	/**
	 * 连接数据库
	 *
	 * @return boolean
	 */
	public function connect() {
		$ret = mysql_connect($this->db_host , $this->db_user , $this->db_password);
		if(!$ret)  $this->halt('Can not connect to database.' , 'Can not connect to database.');
		
		$this->res = $ret;
		
		$ret = $this->selectDB($this->db_name);
		if(!$ret)  $this->halt('Can not select the database.' , 'Can not select the database.');
		
		
		
		$this->query("set names utf8" , '' , false);
		
		return true;
	}

	/**
	 * 选择数据库
	 *
	 * @param string $db_name
	 * @return boolean
	 */
	public function selectDB($db_name) {
		return mysql_select_db($db_name , $this->res);
	}

	/**
	 * 执行SQL
	 *
	 * @param string $sql
	 * @param string $type
	 * @param boolean $halt
	 * @return resource
	 */
	public function query($sql , $type = '' , $halt = true) {
		$func = $type === 'UNBUFFERED' ? 'mysql_unbuffered_query' : 'mysql_query';
		if( !($query_id = $func($sql , $this->res)) && $halt ) {
			echo $sql . '<br />';
			var_dump($this->error());
			// $this->halt('MySQL Query Error' , $this->error() , $this->errno() , $sql);
		}
		++$this->querynum;
		return $query_id;
	}

	/**
	 * 获取数据
	 *
	 * @param resource $query_id
	 * @param constant $type
	 * @return array
	 */
	public function fetchArray($query_id , $type = MYSQL_ASSOC) {
		return mysql_fetch_array($query_id , $type);
	}

	/**
	 * 获取一条数据
	 *
	 * @param string $sql
	 * @param boolean $halt
	 * @return array | false
	 */
	public function result($sql , $halt = true) {
		$query_id = $this->query($sql , '' , $halt);
		if(!$query_id) return false;

		$rs = $this->fetchArray($query_id);
		if(empty($rs)) return false;

		if(!empty($rs) && count($rs) == 1) return array_pop($rs);

		return $rs;
	}

	/**
	 * 获取所有数据
	 *
	 * @param string $sql
	 * @param boolean $halt
	 * @return array
	 */
	public function getAll($sql , $key = false , $halt = true) {
		$query_id = $this->query($sql , '' , $halt);
		if(!$query_id) return array();

		$result = array();
		while ($rs = $this->fetchArray($query_id)) {
			if($key !== false) $result[] = $rs[$key];
			else $result[] = $rs;
		}

		return $result;
	}

	/**
	 * 插入数据 - 数组
	 *
	 * @param string $table
	 * @param array $array
	 * @return resource | false
	 */
	public function doInsert($table , $array ) {
		$formated_array = $this->compileInsertString( $array );
		$query = $this->query('INSERT INTO `'.$table.'` ('.$formated_array['FIELD_NAMES'].') VALUES('.$formated_array['FIELD_VALUES'].')');
		return $query;
	}

	/**
	 * 修改数据 - 数组
	 *
	 * @param string $table
	 * @param array $array
	 * @param string $where
	 * @return resource | false
	 */
	public function doUpdate( $table , $array , $where='' ) {
		$string = $this->compileUpdateString( $array );
		$sql = 'UPDATE `'.$table.'` SET '.$string;
		if ( $where ) {
			$sql .= ' WHERE '.$where;
		}
		$query = $this->query( $sql );
		return $query;
	}

	/**
	 * 编译插入SQL
	 *
	 * @param array $data
	 * @return array
	 */
	public function compileInsertString($data) {
		$field_names  = '';
		$field_values = '';

		foreach ($data as $k => $v) {
			$field_names  .= "`{$k}`,";

			if ( is_numeric( $v ) and intval($v) == $v ) {
				$field_values .= intval($v).",";
			} else {
				$field_values .= "'".self::filter($v)."',";
			}
		}
		$field_names  = preg_replace( "/,$/" , "" , $field_names  );
		$field_values = preg_replace( "/,$/" , "" , $field_values );

		return array( 'FIELD_NAMES'  => $field_names, 'FIELD_VALUES' => $field_values);
	}

	/**
	 * 编译修改SQL - 数组
	 *
	 * @param string $data
	 * @return string
	 */
	public function compileUpdateString($data) {
		$return = '';
		foreach ($data as $k => $v) {
			if ( is_numeric( $v ) and intval($v) == $v ) {
				$return .= "`{$k}`" . "=".intval($v).",";
			} else {
				$return .= "`{$k}`" . "='".self::filter($v)."',";
			}
		}
		$return = preg_replace( "/,$/" , "" , $return );
		return $return;
	}

	/**
	 * 过滤器
	 *
	 * @param string $string
	 * @param boolean $force
	 * @return string
	 */
	public static function filter($string , $force = 0) {
		if ($force == 1 || !get_magic_quotes_gpc()) {
			$string = addslashes($string);
		}
		return $string;
	}

	/**
	 * 关闭数据库链接
	 *
	 * @return boolean
	 */
	public function close() {
		return mysql_close($this->res);
	}

	/**
	 * 获取更新条数
	 *
	 * @return int
	 */
	public function affectedRows() {
		return mysql_affected_rows();
	}

	/**
	 * 获取取到的条数
	 *
	 * @param resource $query_id
	 * @return int
	 */
	public function numRows($query_id) {
		return mysql_num_rows($query_id);
	}

	/**
	 * 获取上次插入id
	 *
	 * @return int
	 */
	public function insertId() {
		return mysql_insert_id();
	}

	/**
	 * 获取错误信息
	 *
	 * @return string
	 */
	public function error() {
		return mysql_error();
	}

	/**
	 * 获取错误号
	 *
	 * @return int
	 */
	public function errno() {
		return intval(mysql_errno());
	}

	/**
	 * 错误处理
	 *
	 * @param string $error_info
	 * @param string $error_msg
	 * @param int $error_no
	 * @param string $error_sql
	 */
	public function halt($error_info , $error_msg = '' , $error_no = '' , $error_sql = '') {
		$content = "<b>Info</b>: " . $error_info . "<br />\n";
		$content .= "<b>Script</b>: " . basename($_SERVER['PHP_SELF']) . ( empty($_SERVER['QUERY_STRING']) ? '' : ( '?' . htmlspecialchars($_SERVER['QUERY_STRING']) ) ) . "<br />\n";
		$content .= "<b>Time</b>: " . date("Y-m-d H:i" , time()) . "<br />\n";
		if(!empty($error_sql))
			$content .= "<b>SQL</b>: " . htmlspecialchars($error_sql) . "<br />\n";
		if(!empty($error_msg))
			$content .= "<b>Error</b>: " . $error_msg . "<br />\n";
		if(!empty($error_no))
			$content .= "<b>Errno</b>: " . $error_no . "<br />\n";
		$content .= "<b>IP address</b>: " . get_client_ip() . "<br />\n\n\n";
		writetofile('db_error_' . date('Ymd') . '.html' , 'error' , $content . "<hr />\n" , 1 , 'a');

		if($this->is_halt) {
			echo "<html>\n<head>\n<style>\n*{font-family:Verdana; font-size: 11px; background: #FFFFFF;}</style>\n</head>\n<body>\n";
			echo $content;
			echo "<br />\nA email has sent to administrator, you can contact me, my email is phzzyzhou@gmail.com<br />\nThank you<br />\n";
			echo "</body>\n</html>";
			exit();
		}
	}
}

# end of script
